package com.silver.weibo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.silver.weibo.dao.LabelMapper;
import com.silver.weibo.entity.Attention;
import com.silver.weibo.entity.Blogs;
import com.silver.weibo.entity.Users;
import com.silver.weibo.entity.vo.UserVO;
import com.silver.weibo.server.AttentionService;
import com.silver.weibo.server.BlogService;
import com.silver.weibo.server.UserService;
import com.silver.weibo.utils.MyContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/index")
public class IndexController {

    private final LabelMapper labelMapper;
    private final UserService userService;
    private final BlogService blogService;
    private final AttentionService attentionService;

    @Autowired
    public IndexController(LabelMapper labelMapper, UserService userService, BlogService blogService, AttentionService attentionService) {
        this.labelMapper = labelMapper;
        this.userService = userService;
        this.blogService = blogService;
        this.attentionService = attentionService;
    }


    @GetMapping("/loginSucc")
    public String succ() {
        // 获取request
        HttpServletRequest request = MyContextUtil.getRequest();
        // 获取得到spring security权限的用户信息
        Principal principal = request.getUserPrincipal();

        if (principal != null) {
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("user_loginname", principal.getName());
            Users users = userService.getOne(wrapper);

            request.getSession().setAttribute("loginUser", principal.getName());

            // 查询博主的粉丝数目
            QueryWrapper<Attention> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("blogger_id", users.id);
            int fans = attentionService.count(wrapper1);

            // 查询博主所有博客点赞的总数 和 博客总数
            QueryWrapper<Blogs> wrapper2 = new QueryWrapper<>();
            wrapper2.select("IFNULL(sum(likes),0) as likes, COUNT(1) as blogNumber")
                    .eq("user_id", users.id);
            // 把查询到的 字段 与 值 存到一个map中
            Map<String, Object> map = blogService.getMap(wrapper2);
            // sum()函数返回值是 BigDecimal,  count()函数返回的是 Long
            BigDecimal bdc = (BigDecimal) map.get("likes");
            Long bgn = (Long) map.get("blogNumber");
            // 把 BigDecimal转成Integer的方法
            Integer likes = Integer.parseInt(bdc.toString());
            Integer blogs = Integer.parseInt(bgn.toString());


            UserVO userVO = new UserVO(users, blogs, fans, likes);

            request.getSession().setAttribute("userVO", userVO);

        }


        return "redirect:/index/list";
    }

    @GetMapping("/list")
    public String list() {
/*        List<Labels> labels = labelMapper.selectList(null);
        // 查询条件
        QueryWrapper<Blogs> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "label", "user_id", "image").orderByDesc("create_time");
        // 分页查询第一行
        Page<Blogs> page = new Page<>(1, 3);
        blogService.page(page, wrapper);
        model.addAttribute("blog1", page.getRecords());
        // 分页查询第二行
        page = new Page<>(2, 3);
        blogService.page(page, wrapper);
        model.addAttribute("blog2", page.getRecords());
        // 设置分页信息
        PageUtil pageUtil = new PageUtil(Math.toIntExact(page.getTotal()), 1, 3);
        List<Integer> pageNumList = pageUtil.countPreAndSufNo();

        // 查询hot排行榜
        getBlogRange(model);


        model.addAttribute("pageNo", pageUtil.getCurrentPageNo())
                .addAttribute("totalPage", pageUtil.getTotalPageNo())
                .addAttribute("pageNumList", pageNumList)
                .addAttribute("labels", labels)
                .addAttribute("pageName", "list");

        return "list";*/
        return "redirect:/blog/pageList?pageNo=1&blogKey=&blogLabel=0";
    }


    @GetMapping("/tologin")
    public String login(Model model) {
        if (model.getAttribute("loginMsg") == null) {
            model.addAttribute("loginMsg", "请先登录");
        }
        return "login";
    }

    @GetMapping("/toreg")
    public String reg() {
        return "reg";
    }

    @PostMapping("/reg")
    public String addUser(Users user, RedirectAttributes attr) {
        user.setUserBirthday(new Date());
        boolean b = userService.save(user);
        if (b) {
            attr.addFlashAttribute("loginMsg", "注册成功，请登录");
        } else {
            attr.addFlashAttribute("loginMsg", "抱歉，注册失败");
        }
        return "redirect:/index/tologin";
    }

    @ResponseBody
    @GetMapping("/checkUserCode")
    public Map<String, String> checkUser(@RequestParam("loginName") String loginName) {

        HashMap<String, String> map = new HashMap<>();
        if (loginName.trim().equals("")) {
            map.put("message", "isNull");
            return map;
        }
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_loginname", loginName)
                .select("user_loginname");
        Users one = userService.getOne(wrapper);

        if (one != null) {
            map.put("message", "exist");
            return map;
        }
        map.put("message", "no");
        return map;
    }


    public void getBlogRange(Model model) {

        QueryWrapper<Blogs> wrapper = new QueryWrapper<>();
        wrapper.select("id", "title", "likes").orderByDesc("likes");
        Page<Blogs> page = new Page<>(1, 5);

        blogService.page(page, wrapper);
        model.addAttribute("likeRange", page.getRecords());


        QueryWrapper<Blogs> wrapper1 = new QueryWrapper<>();
        wrapper1.select("id", "title", "views").orderByDesc("views");

        blogService.page(page, wrapper1);
        model.addAttribute("viewRange", page.getRecords());
    }


}
